import Koa from 'koa'
import dbConfig from '../config/dbConfig'
import errors from './HttpException'
import { catchError } from '../middlewares/exception'
import path from 'path'
import staticFiles from 'koa-static'
import cors from 'koa2-cors'
import { fileDisplay } from '../common/utils/utils'
import session from 'koa-session'
import Config from '../config/Config'
import http from 'http'
import security from '../middlewares/security'
import SocketService from '../service/socket/index'
import Auth from '../middlewares/Auth'
import koaBodyParser from 'koa-bodyparser'
class Init {
  public static app: Koa<Koa.DefaultState, Koa.DefaultContext>
  public static server: http.Server
  public static initCore(app: Koa<Koa.DefaultState, Koa.DefaultContext>, server: http.Server) {
    Init.app = app
    Init.server = server
    //Init.initGlobalVariable()
    Init.loadBodyParser()
    Init.loadCrossDomain()
    Init.initCatchError()
    // Init.initIimitIPTimes()
    Init.loadStatic()
    Init.loadSession()
    Init.initLoadRouters()
    Init.loadSocket()
    Init.updateRedisRole()
  }

  // 解析body参数
  public static loadBodyParser() {
    Init.app.use(koaBodyParser())
  }

  public static initIimitIPTimes() {
    Init.app.use(security)
  }

  public static initGlobalVariable() {
    const globalAny: any = global

    globalAny.dbConfig = dbConfig
    globalAny.errors = errors
    /* global.dbConfig = dbConfig
        global.errors = errors  */
  }

  // 错误监听和日志处理
  public static initCatchError() {
    Init.app.use(catchError)
  }

  // 创建静态资源服务
  public static loadStatic() {
    Init.app.use(staticFiles(path.join(`${process.cwd()}/src/public/`)))
  }

  // 跨域处理
  static loadCrossDomain() {
    Init.app.use(cors())
  }

  // 加载接口
  static async initLoadRouters() {
    const dirPath = path.join(`${process.cwd()}/${Config.base}/api/`)
    await fileDisplay(dirPath, Init.app)
    console.log('接口加载完成')
  }

  // 加载session
  static loadSession() {
    Init.app.keys = ['some secret hurr']
    Init.app.use(
      session(
        {
          key: 'koa:sess', //cookie key (default is koa:sess)
          maxAge: 86400000, // cookie的过期时间 maxAge in ms (default is 1 days)
          overwrite: true, //是否可以overwrite    (默认default true)
          httpOnly: true, //cookie是否只有服务器端可以访问 httpOnly or not (default true)
          signed: true, //签名默认true
          rolling: false, //在每次请求时强行设置cookie，这将重置cookie过期时间（默认：false）
          renew: false, //(boolean) renew session when session is nearly expired,
        },
        Init.app
      )
    )
  }

  static loadSocket() {
    new SocketService(this.server)
    // const io = new socket.Server(this.server, {
    //     allowEIO3: true,
    //     cors: {
    //         // origin: Config.clientURL,
    //         origin: '*',
    //         methods: ["GET", "POST"],
    //         credentials: true,
    //     }
    // })
    // // const io = require('socket.io')(this.server);
    // io.on('connection', (socket: { on: (arg0: string, arg1: (data: any) => void) => void; emit: (arg0: string, arg1: { hello: string }) => void }) => {
    //     console.log('socket初始化完成');
    //     socket.on('disconnect', () => {
    //     console.log('user disconnected');
    //     });
    //     socket.on('message', data => {
    //         console.log(data, '接收到的信息')
    //         socket.emit('serverMessage', {hello: '你是谁'})
    //     })
    //     socket.on('userSay', data => {
    //         console.log(data, 'userSay')
    //         socket.emit('message', {hello: '你是谁'})
    //     })
    // })
  }

  // 更新redis里的角色数据
  public static updateRedisRole() {
    Auth.updateRedisRole()
  }
}

export default Init.initCore
